using Google.Protobuf;
using Shioho.Net;
using ShiohoNet;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static ShiohoNet.ShiohoNetMsgProvider;

public class DemoWs : MonoBehaviour
{
    private ProtoWebsocket _ws;
    private ShiohoNetMsgProvider _provider;

    void Start()
    {
        _provider = new ShiohoNetMsgProvider();
        _ws = new ProtoWebsocket(@"ws://127.0.0.1:4396");
        _ws.OnProtoResponseMsg = OnResponseMsg;
        _ws.OnProtoPushMsg = OnPushMsg;

        _ws.Connect();

    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A)) 
        {
            var req = new GetPlayerRequest();
            req.PlayerId = "10086";
            SendRequest(EShiohoNetProtoId.GetPlayer, req);
        }
    }

    private void OnDestroy()
    {
        _ws.Disconnect();
    }

    private void OnResponseMsg(ProtoResponseData response)
    {
        var msgCtrl = _provider.GetSendMsgCtrl(response.ProtoId);
        msgCtrl?.Process(response.SeqId, response.Msg);
    }

    private void OnPushMsg(ProtoPushData push)
    {
        var msgCtrl = _provider.GetPushMsgCtrl(push.ProtoId);
        msgCtrl?.Process(push.Msg);
    }

    private void SendRequest(EShiohoNetProtoId protoId, IMessage data, object context = null)
    {
        var msgCtrl = _provider.GetSendMsgCtrl((int)protoId);
        if (msgCtrl == null)
            return;

        msgCtrl.AddContext(_ws.SeqId, context);
        var buffer = msgCtrl.GetBuffer(_ws.SeqId, data);
        _ws?.SendBinary(buffer);
    }
}
